package com.cqan.account.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.cqan.account.entity.Authority;
import com.cqan.account.entity.Role;
import com.cqan.account.entity.User;
import com.cqan.account.service.RoleService;
import com.cqan.account.service.UserService;

/**
 * @author wuhui
 *
 * 上午10:16:00
 */
@Service("userDetailsService")
public class UserDetailServiceImpl implements UserDetailsService {

	private Logger logger = Logger.getLogger("ds.debug");
	private UserService userService;
	private RoleService roleService;
	
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		
		logger.debug("loginName is " + username);  
        User user = this.userService.getUserByUserName(username);  
        if(user == null) {  
            throw new UsernameNotFoundException(username);  
        }  
        List<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user);  
        user.setAuthorities(Collections.unmodifiableList(grantedAuths));
        return user;  
	}
	
	
	
	//取得用户的权限  
    private List<GrantedAuthority> obtionGrantedAuthorities(User user) {  
    	List<GrantedAuthority> authSet = new ArrayList<GrantedAuthority>();  
        List<Role> roles = user.getRoles();  
          
        for(Role role : roles) {  
        	role = roleService.get(role.getId());
        	List<Authority>  Authorities = role.getAuthorities();  
            if (Authorities==null) {
				return authSet;
			}
            for(Authority authority : Authorities) {  
                authSet.add(new GrantedAuthorityImpl(String.valueOf(authority.getId())));  
           }  
        }  
        return authSet;  
    }  

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@Autowired
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

}
